package cn.supermaster.management.web.service.system.impl;

import cn.supermaster.management.common.constant.UserConstant;
import cn.supermaster.management.common.domain.SystemRole;
import cn.supermaster.management.common.domain.SystemUser;
import cn.supermaster.management.common.page.TableDataInfo;
import cn.supermaster.management.common.response.WebResponse;
import cn.supermaster.management.common.utils.ShiroUtils;
import cn.supermaster.management.common.utils.TextUtils;
import cn.supermaster.management.common.utils.WebHelper;
import cn.supermaster.management.common.utils.poi.ExcelUtil;
import cn.supermaster.management.core.component.PasswordManager;
import cn.supermaster.management.system.domain.SystemPost;
import cn.supermaster.management.system.service.ISystemPostService;
import cn.supermaster.management.system.service.ISystemRoleService;
import cn.supermaster.management.system.service.ISystemUserService;
import cn.supermaster.management.web.service.system.ISUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.web.service.system.impl
 * @ClassName: SUserServiceImpl
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/1/11 2:44
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.comn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Service
public class SUserServiceImpl implements ISUserService {

    private String prefix = "system/user";

    @Autowired
    private ISystemUserService userService;

    @Autowired
    private ISystemRoleService roleService;

    @Autowired
    private ISystemPostService postService;

    @Autowired
    private PasswordManager passwordManager;

    /*
     * ================================================
     *  页面跳转功能实现
     * ================================================
     */

    /**
     * @Description: [跳转到用户Index页面]
     * <p></P>
     * @Title: skipUserIndexHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Return: java.lang.String
     */
    @Override
    public String skipUserIndexHtml() {
        return prefix + "/user";
    }

    /**
     * @param modelMap
     * @Description: [跳转到用户新增页面]
     * <p></P>
     * @Title: skipAddUserHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipAddUserHtml(ModelMap modelMap) {
        //
        List<SystemRole> roles = roleService.selectRoleAll()
                .stream().filter(r -> !r.isAdmin())
                .collect(Collectors.toList());
        modelMap.put("roles", roles);
        //
        List<SystemPost> posts = postService.selectPostAll();
        modelMap.put("posts", posts);

        return prefix + "/add";
    }

    /**
     * @Description: [跳转修改用户界面]
     * <p></P>
     * @Title: skiModifyUserHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Param: userId
     * @Return: java.lang.String
     */
    @Override
    public String skiModifyUserHtml(ModelMap modelMap, Long userId) {

        //
        SystemUser user = userService.selectUserById(userId);
        modelMap.put("user", user);
        //
        boolean isAdmin = SystemUser.isAdmin(userId);
        List<SystemRole> roles = roleService.selectRolesByUserId(userId);
        List<SystemRole> roles_ = roles.stream()
                .filter(r -> !r.isAdmin())
                .collect(Collectors.toList());
        modelMap.put("roles", isAdmin ? roles : roles_);
        //
        List<SystemPost> posts = postService.selectPostsByUserId(userId);
        modelMap.put("posts", posts);
        //
        return prefix + "/edit";
    }

    /**
     * @Description: [跳转修改用户密码界面]
     * <p></P>
     * @Title: skiResetPasswordHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Param: userId
     * @Return: java.lang.String
     */
    @Override
    public String skiResetPasswordHtml(ModelMap modelMap, Long userId) {
        SystemUser user = userService.selectUserById(userId);
        modelMap.put("user", user);
        return prefix + "/resetPwd";
    }

    /**
     * @Description: [进入授权角色页]
     * <p></P>
     * @Title: skipAuthRoleHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Param: userId
     * @Return: java.lang.String
     */
    @Override
    public String skipAuthRoleHtml(ModelMap modelMap, Long userId) {
        SystemUser user = getSystemUser(userId);
        modelMap.put("user", user);
        // 获取用户所属的角色列表
        boolean isAdmin = SystemUser.isAdmin(userId);
        List<SystemRole> roles = roleService.selectRolesByUserId(userId);
        List<SystemRole> filterRoles = roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());
        modelMap.put("roles", isAdmin ? roles : filterRoles);

        return prefix + "/authRole";
    }

    /*
     * ================================================
     *  Rest功能实现
     * ================================================
     */

    /**
     * @Description: [根据条件获取用户信息列表]
     * <p></P>
     * @Title: queryUserListByCondition
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: cn.supermaster.management.common.page.TableDataInfo
     */
    @Override
    public TableDataInfo queryUserListByCondition(SystemUser user) {
        WebHelper.startPage();
        List<SystemUser> list = userService.selectUserList(user);
        TableDataInfo result = WebHelper.getDataTable(list);
        return result;
    }

    /**
     * @Description: [导出用户信息列表]
     * <p></P>
     * @Title: doExportUserInformation
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doExportUserInformation(SystemUser user) {
        List<SystemUser> list = userService.selectUserList(user);
        ExcelUtil<SystemUser> util = new ExcelUtil<SystemUser>(SystemUser.class);
        return util.exportExcel(list, "用户数据");
    }

    /**
     * @Description: [导入用户信息数据]
     * <p></P>
     * @Title: doImportUserInformation
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: file
     * @Param: updateSupport
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doImportUserInformation(MultipartFile file, boolean updateSupport) {
        String message = "";
        WebResponse result = null;
        try {
            ExcelUtil<SystemUser> util = new ExcelUtil<SystemUser>(SystemUser.class);

            InputStream inputStream = file.getInputStream();
            List<SystemUser> userList = util.importExcel(inputStream);
            String operName = ShiroUtils.getSystemUser().getUserName();
            message = userService.importUser(userList, updateSupport, operName);

            result = WebResponse.success(message);
        } catch (Exception e) {
            result = WebResponse.failure(e.getMessage());
        }
        return result;
    }

    /**
     * @Description: [导入用户模板数据]
     * <p></P>
     * @Title: doImportUserTemplate
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doImportUserTemplate() {
        ExcelUtil<SystemUser> util = new ExcelUtil<SystemUser>(SystemUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * @Description: [新增保存用户]
     * <p></P>
     * @Title: doAddUserInformation
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doAddUserInformation(SystemUser user) {
        String userName = user.getUserName();
        if (UserConstant.USER_NAME_NOT_UNIQUE.equals(userService.checkuserNameUnique(userName))) {
            return WebHelper.error("新增用户'" + userName + "'失败，登录账号已存在");
        } else if (TextUtils.isNotEmpty(user.getMobile())
                && UserConstant.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return WebHelper.error("新增用户'" + userName + "'失败，手机号码已存在");
        } else if (TextUtils.isNotEmpty(user.getEmail())
                && UserConstant.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return WebHelper.error("新增用户'" + userName + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordManager.encryptPassword(userName, user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getuserName());
        return WebHelper.webResult(userService.insertUser(user));
    }

    /**
     * @Description: [修改保存用户]
     * <p></P>
     * @Title: doModifyUserInformation
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doModifyUserInformation(SystemUser user) {
        userService.checkUserAllowed(user);

        String userName = user.getUserName();
        String mobile = user.getMobile();
        String email = user.getEmail();

        if (TextUtils.isNotEmpty(mobile)
                && UserConstant.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return WebHelper.error("修改用户'" + userName + "'失败，手机号码已存在");
        } else if (TextUtils.isNotEmpty(email)
                && UserConstant.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return WebHelper.error("修改用户'" + userName + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getuserName());
        return WebHelper.webResult(userService.updateUser(user));
    }

    /**
     * @Description: [重置密码]
     * <p></P>
     * @Title: doResetPassword
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doResetPassword(SystemUser user) {
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        //
        Long userId = user.getUserId();
        String userName = user.getUserName();
        String password = user.getPassword();
        String salt = user.getSalt();
        user.setPassword(passwordManager.encryptPassword(userName, password, salt));
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId().longValue() == userId.longValue()) {
                ShiroUtils.setSystemUser(userService.selectUserById(userId));
            }
            return WebHelper.success();
        }
        return WebHelper.error();
    }

    /**
     * @Description: [用户授权角色]
     * <p></P>
     * @Title: doInsertAuthRole
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: userId
     * @Param: roleIds
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doInsertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return WebHelper.success();
    }

    /**
     * @Description: [删除用户信息]
     * <p></P>
     * @Title: doRemoveUserInformation
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: ids
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doRemoveUserInformation(String ids) {
        return WebHelper.webResult(userService.deleteUserByIds(ids));
    }

    /**
     * @Description: [校验用户名]
     * <p></P>
     * @Title: doCheckuserNameUnique
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: java.lang.String
     */
    @Override
    public String doCheckuserNameUnique(SystemUser user) {
        return userService.checkuserNameUnique(user.getUserName());
    }

    /**
     * @Description: [校验手机号码]
     * <p></P>
     * @Title: doCheckMobileUnique
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: java.lang.String
     */
    @Override
    public String doCheckMobileUnique(SystemUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * @Description: [校验email邮箱]
     * <p></P>
     * @Title: doCheckEmailUnique
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: java.lang.String
     */
    @Override
    public String doCheckEmailUnique(SystemUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * @Description: [用户状态修改]
     * <p></P>
     * @Title: doChangeUserStatus
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: user
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doChangeUserStatus(SystemUser user) {
        userService.checkUserAllowed(user);
        return WebHelper.webResult(userService.changeStatus(user));
    }

    /*
     * ================================================
     *
     * ================================================
     */

    /**
     * @Description: []
     * <p></P>
     * @Title: getSystemUser
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: userId
     * @Return: cn.supermaster.management.common.domain.SystemUser
     */
    private SystemUser getSystemUser(Long userId) {
        SystemUser user = userService.selectUserById(userId);
        return user;
    }

}